Page({
  data: {
    isRegister: false,
    username: 'admin',
    password: '12345',
    repassword: '',
    captcha: '',
    captchaUrl: '',
    key: ''
  },

  onLoad() {
    this.fetchCaptcha();
  },

  inputUsername(e) {
    this.setData({ username: e.detail.value });
  },

  inputPassword(e) {
    this.setData({ password: e.detail.value });
  },

  inputRepassword(e) {
    this.setData({ repassword: e.detail.value });
  },

  inputCaptcha(e) {
    this.setData({ captcha: e.detail.value });
  },

  toggleForm() {
    this.setData({ isRegister: !this.data.isRegister });
    this.fetchCaptcha();
  },

  fetchCaptcha() {
    const key = Math.random().toString();
    this.setData({ key });
    wx.request({
      url: 'http://localhost:8080/captcha?key=' + key,
      method: 'GET',
      responseType: 'arraybuffer',
      success: (res) => {
        const arrayBuffer = res.data;
        const base64 = wx.arrayBufferToBase64(arrayBuffer);
        this.setData({ captchaUrl: 'data:image/png;base64,' + base64 });
      },
      fail: (err) => {
        console.error('获取验证码失败:', err);
      }
    });
  },

  refreshCaptcha() {
    this.fetchCaptcha();
  },

  register() {
    const { username, password, repassword, captcha, key } = this.data;
    if (password !== repassword) {
      wx.showToast({ title: '两次输入的密码不一致', icon: 'none' });
      return;
    }
    wx.request({
      url: 'http://localhost:8080/register',
      method: 'POST',
      data: { username, password, captcha, key },
      success: (res) => {
        if (res.data.msg === '操作成功') {
          wx.showToast({ title: '注册成功' });
          this.setData({ isRegister: false });
          this.fetchCaptcha();
        } else {
          wx.showToast({ title: `注册失败: ${res.data.msg || '未知错误'}`, icon: 'none' });
          this.fetchCaptcha();
        }
      },
      fail: (err) => {
        console.error('注册请求失败:', err);
        wx.showToast({ title: '注册请求失败，请稍后再试', icon: 'none' });
        this.fetchCaptcha();
      }
    });
  },

  login() {
   
    const { username, password, captcha, key } = this.data;
    wx.request({
      url: 'http://localhost:8080/user/login',
      method: 'POST',
      data: { username, password, captcha, key },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded' // 确保这是默认值
      },
      success: (res) => {
        if (res.data.msg === '操作成功') {
          wx.setStorageSync('token', res.data.data);
          wx.switchTab({ url: '/pages/index/index' });
          wx.showToast({ title: '登录成功' });
        } else {
          wx.showToast({ title: `登录失败: ${res.data.msg || '未知错误'}`, icon: 'none' });
          this.fetchCaptcha();
        }
      },
      fail: (err) => {
        console.error('登录请求失败:', err);
        wx.showToast({ title: '登录请求失败，请稍后再试', icon: 'none' });
        this.fetchCaptcha();
      }
    });
  }
});
